import React, { useEffect } from 'react'
import styles from './LoginForm.module.css'
// import { Spin } from 'antd'
import { Form, Input, Button, Checkbox } from 'antd'
import { useNavigate } from 'react-router-dom'
import { signIn } from '../../redux/user/slice'
import { useAppDispatch, useSelector } from '../../redux/hook'
const layout = {
  labelCol: { span: 8 },
  wrapperCol: { span: 16 }
}
const tailLayout = {
  wrapperCol: { offset: 8, span: 16 }
}
export const LoginForm: React.FC = () => {
  const loading = useSelector((s) => s.user.loading)
  const jwt = useSelector((s) => s.user.jwt)
  // const error = useSelector((s) => s.user.error)
  const dispatch = useAppDispatch()
  const navigate = useNavigate()
  useEffect(() => {
    if (jwt) {
      navigate('/')
    }
  }, [jwt, navigate])
  const onFinish = (values: any) => {
    dispatch(
      signIn({
        email: values.username,
        password: values.password
      })
    )
  }

  const onFinishFailed = (errorInfo: any) => {
    console.log('Failed:', errorInfo)
  }
  // if (loading) {
  //   return (
  //     <Spin
  //       size="large"
  //       style={{
  //         marginTop: 200,
  //         marginBottom: 200,
  //         marginLeft: 'auto',
  //         marginRight: 'auto',
  //         width: '100%'
  //       }}
  //     ></Spin>
  //   )
  // }
  // if (error) {
  //   return <div>网站出错：{error}</div>
  // }
  return (
    <Form
      {...layout}
      name="basic"
      initialValues={{ remember: true }}
      onFinish={onFinish}
      onFinishFailed={onFinishFailed}
      className={styles['register-form']}
    >
      <Form.Item
        label="Username"
        name="username"
        rules={[{ required: true, message: 'Please input your username!' }]}
      >
        <Input />
      </Form.Item>

      <Form.Item
        label="Password"
        name="password"
        rules={[{ required: true, message: 'Please input your password!' }]}
      >
        <Input.Password />
      </Form.Item>

      <Form.Item {...tailLayout} name="remember" valuePropName="checked">
        <Checkbox>Remember me</Checkbox>
      </Form.Item>

      <Form.Item {...tailLayout}>
        <Button type="primary" htmlType="submit" loading={loading}>
          Submit
        </Button>
      </Form.Item>
    </Form>
  )
}
